#include "SSerial.h"
#include "Digital.h"


SSerial::SSerial(uint16_t Speed, uint8_t receivePin, uint8_t transmitPin) {
	ReceivePin = receivePin;
	TransmitPin = transmitPin;
	BaudRate = Speed;
	BitPeriod = 1000000 / BaudRate;

	DigitalWrite(TransmitPin, HIGH);
	DelayMicroseconds(BitPeriod); // if we were low this establishes the end
}

int SSerial::Read() {
  int val = 0;
  int bitDelay = BitPeriod - ClockCyclesToMicroseconds(50);

  // one byte of serial data (LSB first)
  // ...--\    /--\/--\/--\/--\/--\/--\/--\/--\/--...
  //	 \--/\--/\--/\--/\--/\--/\--/\--/\--/
  //	start  0   1   2   3   4   5   6   7 stop

  while (DigitalRead(ReceivePin));

  // confirm that this is a real start bit, not line noise
  if (DigitalRead(ReceivePin) == LOW) {
    // frame start indicated by a falling edge and low start bit
    // jump to the middle of the low start bit
	 DelayMicroseconds(bitDelay / 2 - ClockCyclesToMicroseconds(50));

    // offset of the bit in the byte: from 0 (LSB) to 7 (MSB)
    for (int offset = 0; offset < 8; offset++) {
	// jump to middle of next bit
    DelayMicroseconds(bitDelay);

	// read bit
	val |= DigitalRead(ReceivePin) << offset;
    }

    DelayMicroseconds(BitPeriod);

    return val;
  }

  return -1;
}



